package floatWindow2.rom;/*
 * Copyright (C) 2016 Facishare Technology Co., Ltd. All Rights Reserved.
 */


import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.example.livesettingtest.MyConstant;
import com.example.livesettingtest.R;

import java.lang.reflect.Method;

import floatWindow2.FloatActionController;

public class HuaweiUtils {
    private static final String TAG = "HuaweiUtils";
    static Context mContext;

    public static HuaweiUtils getInstance(Context context) {
        mContext = context;
        return HuaweiUtils.LittleMonkProviderHolder.sInstance;
    }

    // 静态内部类
    private static class LittleMonkProviderHolder {
        private static final HuaweiUtils sInstance = new HuaweiUtils();
    }
    /**
     * 检测 Huawei 悬浮窗权限
     */
    public static boolean checkFloatWindowPermission(Context context) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 19) {
            return checkOp(context, 24); //OP_SYSTEM_ALERT_WINDOW = 24;
        }
        return true;
    }

    /**
     * 去华为权限申请页面
     */
    public static void applyPermission(Context context) {
        try {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//   ComponentName comp = new ComponentName("com.huawei.systemmanager","com.huawei.permissionmanager.ui.MainActivity");//华为权限管理
//   ComponentName comp = new ComponentName("com.huawei.systemmanager",
//      "com.huawei.permissionmanager.ui.SingleAppActivity");//华为权限管理，跳转到指定app的权限管理位置需要华为接口权限，未解决
            ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.addviewmonitor.AddViewMonitorActivity");//悬浮窗管理页面
            intent.setComponent(comp);
            if (RomUtils.getEmuiVersion() == 3.1) {
                //emui 3.1 的适配
                context.startActivity(intent);
            } else {
                //emui 3.0 的适配
                comp = new ComponentName("com.huawei.systemmanager", "com.huawei.notificationmanager.ui.NotificationManagmentActivity");//悬浮窗管理页面
                intent.setComponent(comp);
                context.startActivity(intent);
            }
        } catch (SecurityException e) {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//   ComponentName comp = new ComponentName("com.huawei.systemmanager","com.huawei.permissionmanager.ui.MainActivity");//华为权限管理
            ComponentName comp = new ComponentName("com.huawei.systemmanager",
                    "com.huawei.permissionmanager.ui.MainActivity");//华为权限管理，跳转到本app的权限管理页面,这个需要华为接口权限，未解决
//      ComponentName comp = new ComponentName("com.huawei.systemmanager","com.huawei.systemmanager.addviewmonitor.AddViewMonitorActivity");//悬浮窗管理页面
            intent.setComponent(comp);
            context.startActivity(intent);
            Log.e(TAG, Log.getStackTraceString(e));
        } catch (ActivityNotFoundException e) {
            /**
             * 手机管家版本较低 HUAWEI SC-UL10
             */
//   Toast.makeText(MainActivity.this, "act找不到", Toast.LENGTH_LONG).show();
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.Android.settings", "com.android.settings.permission.TabItem");//权限管理页面 android4.4
//   ComponentName comp = new ComponentName("com.android.settings","com.android.settings.permission.single_app_activity");//此处可跳转到指定app对应的权限管理页面，但是需要相关权限，未解决
            intent.setComponent(comp);
            context.startActivity(intent);
            e.printStackTrace();
            Log.e(TAG, Log.getStackTraceString(e));
        } catch (Exception e) {
            //抛出异常时提示信息
            Toast.makeText(context, "进入设置页面失败，请手动设置", Toast.LENGTH_LONG).show();
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private static boolean checkOp(Context context, int op) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 19) {
            AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            try {
                Class clazz = AppOpsManager.class;
                Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class);
                return AppOpsManager.MODE_ALLOWED == (int) method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName());
            } catch (Exception e) {
                Log.e(TAG, Log.getStackTraceString(e));
            }
        } else {
            Log.e(TAG, "Below API 19 cannot invoke!");
        }
        return false;
    }


    /*g xw+s for 自启动START */
    /**
     * 打开自启动设置页面，android 8.0，9.0，7.0都可以打开，只是getTipTypeAutoStart应返回不同的提示
     * 因为各个操作系统都不一样
     *
     *
     */

    /**
     * 由于设置自启动的方式 各操作系统都不一样，所以需要具体情况返回准确的值
     * @return
     */
    static public MyConstant.tipType getTipTypeAutoStart(boolean isBelowAndroid7)
    {
        if(isBelowAndroid7)
        {
            return  MyConstant.tipType.AUTO_START7;
        }
        else
        {
            return  MyConstant.tipType.AUTO_START;
        }

    }

    /**
     * 打开浮动窗口
     */
    static public void openFloatWindowTip( MyConstant.tipType floatWindowType, boolean isPermission) {

        //有对应权限或者系统版本小于7.0
        if (isPermission || Build.VERSION.SDK_INT < 24) {  //gxw:也就是android 6.0以下，这里需要在6.0以下的手机上测试一下
            //开启悬浮窗
            FloatActionController.getInstance().startMonkServer(mContext,floatWindowType);
        }

        return;
    }
    static public void openAutoStart(boolean isBelowAndroid7,boolean IsPermissionFloat) {
        ComponentName componentName = null;
        componentName = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity");
        Intent intent = new Intent();
        intent.setComponent(componentName);
        try {
            mContext.startActivity(intent);
            MyConstant.tipType tipType = getTipTypeAutoStart(isBelowAndroid7);
            openFloatWindowTip(tipType,IsPermissionFloat);


        } catch (Exception e) {

            try {
                openMobileManager(IsPermissionFloat);  //如果异常，优先打开手机管家
                openFloatWindowTip(MyConstant.tipType.MOBILE_MANAGER,IsPermissionFloat);

            } catch (Exception e1) {
                //最坏的情况下，是打开设置页面
                dealErrorSkip(e1,IsPermissionFloat);
            }

        }
    }


    /**
     * 打开华为手机管家
     */
    static  public void openMobileManager(boolean isPermission) {

        ComponentName componentName = null;
        componentName = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.mainscreen.MainScreenActivity");
        Intent intent = new Intent();
        intent.setComponent(componentName);
        mContext.startActivity(intent);
    }


    static public void dealErrorSkip(Exception e,boolean isPermissionFloat) {

        Toast.makeText(mContext, "不兼容", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
        Log.i(TAG, e.getMessage());
        Intent intent = new Intent(Settings.ACTION_SETTINGS);
        mContext.startActivity(intent);
        //gxw3- openFloatWindowTip(MyConstant.tipType.SETTINGS,isPermissionFloat);
    }
    /*gxw+e 自启动END*/


    /*gxw+s*/

    /**
     * 打开权限
     * * <p>
     * * Input: The Intent's data URI specifies the application package name
     * * to be shown, with the "package" scheme.  That is "package:com.my.app".
     * * <p>
     * * Output: Nothing.
     */

    public void openPermission(MyConstant.tipType tipType,boolean isPermission) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("package:" + mContext.getPackageName()));
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        //gxw-intent.setAction(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);打开浮动窗口权限

        try {
            if(tipType == MyConstant.tipType.PERMISSION) {
                Toast toast = Toast.makeText(mContext, R.string.permission,Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
            mContext.startActivity(intent);
            openFloatWindowTip(tipType,isPermission);
        } catch (Exception e) {
            dealErrorSkip(e,isPermission);
        }
        return;
    }

    /*gxw+e*/


    /**
     * 锁屏清理
     */
    public void lockScreenClear(boolean isPermission)
    {
        try {
            ComponentName componentName = null;
            componentName = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity");
            Intent intent = new Intent();
            intent.setComponent(componentName);
            mContext.startActivity(intent);
            openFloatWindowTip(MyConstant.tipType.LOCK_SCREEN,isPermission);
        } catch (Exception e) {
            dealErrorSkip(e,isPermission);
            e.printStackTrace();
        }
        return;
    }


    /**
     * 打开通知设置
     */
    public void openNotifySetting(boolean isBelowAndroid7,boolean isPermission) {

        if(isBelowAndroid7)
        {
            openPermission(MyConstant.tipType.PERMISSION_NOTIFY,isPermission);
        }
        else
        {
            String packageName = mContext. getPackageName();
            int appUid = mContext.getApplicationInfo().uid;
            Log.i(TAG, "packageName=" + packageName + ",appUid=" + appUid);
            Intent intent = new Intent();
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");

            //for Android 5-7
            intent.putExtra("app_package", packageName);
            intent.putExtra("app_uid", appUid);

            // for Android O
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, packageName);

            try {
                mContext.startActivity(intent);
                openFloatWindowTip(MyConstant.tipType.NOTIFY_SETTING,isPermission);
            } catch (Exception e) {
                dealErrorSkip(e,isPermission);
            }
        }
        return;
    }

    /**
     * 忽略电池优化,即白名单
     */
    public void openIgnorBattery(boolean isPermission) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
        try {
            mContext.startActivity(intent);
            openFloatWindowTip(MyConstant.tipType.IGNORE_BATTERY,isPermission);
        } catch (Exception e) {
            dealErrorSkip(e,isPermission);
        }
        return;
    }

    /**
     * 打开WLAN设置，然后点击底部的配置按钮，设置WLAN永不休眠
     */
    public void openWlanSetting(boolean isPermission) {
        ComponentName componentName = null;
        componentName = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.power.ui.PowerSettingActivity");

        Intent intent = new Intent();
        intent.setComponent(componentName);
        int appUid = mContext.getApplicationInfo().uid;
        intent.putExtra("app_uid", appUid);

        try {
            mContext.startActivity(intent);
            openFloatWindowTip(MyConstant.tipType.WLAN_ALWAYS,isPermission);
        } catch (Exception e) {

            try {
                openWlanSetting2(isPermission);   //就近原则，跳转到省电模式（然后点击--更多省电模式--设置WLAN始终连接）
                openFloatWindowTip(MyConstant.tipType.BATTERY_WLAN,isPermission);
            } catch (Exception e1) {
                dealErrorSkip(e1,isPermission);
                e.printStackTrace();
            }
        }
        return;
    }



    public void openWlanSetting2(boolean isPermission) {
        String mtype = android.os.Build.MODEL;  //判断具体型号
        //gxw-   if(mtype.equals("RNE-AL00")) //畅享7S android8.0       STF-AL00华为荣耀9 android8.0.0
        {
            ComponentName componentName = null;
            componentName = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.power.ui.HwPowerManagerActivity");

            Intent intent = new Intent();
            intent.setComponent(componentName);
            int appUid = mContext.getApplicationInfo().uid;
            String packageName = mContext.getPackageName();
            intent.putExtra("app_package", packageName);
            intent.putExtra("app_uid", appUid);
            mContext.startActivity(intent);
        /*    try {
                   mContext.startActivity(intent);
            } catch (Exception e) {
                dealErrorSkip(e,isPermission);
            }*/
        }
   /* Intent i = new Intent(); WLAN开关
      i.setClassName("com.android.settings", "com.android.settings.Settings$WifiSettingsActivity");
      startActivity(i);*/
    }

    public void toastTip(int tipResId)
    {
        Toast toast = Toast.makeText(mContext,tipResId,Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }
}


